import Vue from 'vue';
import Router from 'vue-router';

const Login = () => import('../pages/Login');
const Layout = () => import('../pages/Layout');
// 菜单管理
const Menu = () => import('../pages/menu/Index');
// 角色管理
const Role = () => import('../pages/role/Index');
// 管理员管理
const Admin = () => import('../pages/admin/Index');
// 分类管理
const Cate = () => import('../pages/cate/Index');
// 规格管理
const Specs = () => import('../pages/specs/Index');
// 商品管理
const Goods = () => import('../pages/goods/Index');
// 404
const NotFound = () => import('../pages/NotFound');


// 导入Home
const Home = () => import('../pages/Home');



Vue.use(Router);

// 定义路由规则
const routes = [{
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '管理员登录'
    }
  },
  {
    path: '/',
    component: Layout,
    meta: {
      title: '小U商城后台管理系统'
    },
    redirect: '/home',
    children: [{
        path: '/home',
        component: Home,
        meta: {
          title: '管理中心'
        }
      },
      {
        path: '/menu',
        component: Menu,
        meta: {
          title: '菜单管理'
        }
      },
      {
        path: '/role',
        component: Role,
        meta: {
          title: '角色管理'
        }
      },
      {
        path: '/admin',
        component: Admin,
        meta: {
          title: '管理员管理'
        }
      },
      {
        path: '/category',
        component: Cate,
        meta: {
          title: '分类管理'
        }
      },
      {
        path: '/specs',
        component: Specs,
        meta: {
          title: '规格管理'
        }
      },
      {
        path: '/goods',
        component: Goods,
        meta: {
          title: '商品管理'
        }
      }
    ]
  },
  // 404路由
  {
    path: '*',
    component: NotFound,
    meta: {
      title: '404'
    }
  }
];

const router = new Router({
  routes
});

// 路由导航守卫
router.beforeEach(function (to, from, next) {
  // 如果用户访问的是非登录页面
  // 读取本地存储
  const loginInfo = JSON.parse(localStorage.getItem('loginInfo') || '{}');
  if (to.path !== '/login') {
    // 如果没有登录凭证
    if (!loginInfo.token) {
      return next('/login');
    }
    // 校验访问权限
    const menusUrl = loginInfo.menus_url;
    menusUrl.push('/home');
    if (menusUrl.indexOf(to.path) === -1) {
      return next('/home');
    }
  }

  next();
  // 动态设置页面标题
  document.title = to.meta.title;
});

export default router;
